﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.Windows.Media.Imaging;
using System.IO;

namespace SilverMap.Editor
{
    public partial class TileLoaderWindow : ChildWindow
    {
		public TileLoaderWindow()
        {
            InitializeComponent();
        }

        private void CreateButton_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			var fdOpen = new OpenFileDialog { Multiselect = true, Filter = "PNG files|*.png|JPEG files|*.jpg" };
			if (fdOpen.ShowDialog() == true)
			{
				var id = 0;
				MapManager.Tiles.Clear();
				foreach (var file in fdOpen.Files)
				{
					var name = file.Name;
					var buffer = new byte[file.Length];
					using (var fs = file.OpenRead())
					{
						fs.Read(buffer, 0, buffer.Length);
					}

					var img = new BitmapImage { CreateOptions = BitmapCreateOptions.None };
					img.SetSource(new MemoryStream(buffer));
					var bmp = new WriteableBitmap(img);

					MapManager.Tiles.Add(new Tile
					{
						ID = id++,
						ImageName = name,
						Image = bmp
					});
				}

				SaveButton.IsEnabled = true;
			}
		}

		private void SaveButton_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			var fdSave = new SaveFileDialog { DefaultExt = "xml", Filter = "Tile XML files|*.xml" };
			if (fdSave.ShowDialog() == true)
			{
				using (var file = fdSave.OpenFile())
				{
					MapManager.Tiles.Save(file);
				}

				this.DialogResult = true;
			}
		}

        private void LoadButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
			var fdOpen = new OpenFileDialog { Multiselect = false, Filter = "Tile XML files|*.xml" };
			if (fdOpen.ShowDialog() == true)
			{
				using (var fs = fdOpen.File.OpenRead())
				{
					MapManager.Tiles.Load(fs);
				}

				this.DialogResult = true;
			}
        }
    }
}

